package com.example.docmanagement.service;


import com.example.docmanagement.dto.request.CustomerCreateRequest;
import com.example.docmanagement.dto.request.CustomerUpdateRequest;
import com.example.docmanagement.dto.response.CustomerResponse;
import com.example.docmanagement.dto.response.PageResponse;
import com.example.docmanagement.entity.Customer;
import com.example.docmanagement.entity.User;
import com.example.docmanagement.exception.DuplicateResourceException;
import com.example.docmanagement.exception.ResourceNotFoundException;
import com.example.docmanagement.repository.CustomerRepository;
import com.example.docmanagement.repository.UserRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


@Service
@RequiredArgsConstructor
public class CustomerService {

    private final CustomerRepository customerRepository;
    private final UserRepository userRepository;

    /**
     * 获取客户列表
     * @param status 客户状态
     * @param page 页码
     * @param pageSize 每页数量
     * @param sortBy 排序字段
     * @param sortOrder 排序顺序
     * @return 客户列表
     */
    public PageResponse<CustomerResponse> getCustomers(String status, Integer page, Integer pageSize, String sortBy, String sortOrder){

        // 构建分页参数
        Sort sort = Sort.by(
                "desc".equalsIgnoreCase(sortOrder) ? Sort.Direction.DESC : Sort.Direction.ASC,
                sortBy);
        Pageable pageable = PageRequest.of(page - 1, pageSize, sort);

        Page<CustomerResponse> customers = customerRepository.searchCustomersWithStatus(status, pageable);

        return PageResponse.<CustomerResponse>builder()
                .data(customers.getContent())
                .page(page)
                .pageSize(pageSize)
                .total(customers.getTotalElements())
                .totalPages(customers.getTotalPages())
                .hasNext(customers.hasNext())
                .hasPrevious(customers.hasPrevious())
                .build();
    }

    /**
     * 获取客户详情
     * @param id 客户ID
     * @return 客户详情
     */
    public CustomerResponse getCustomerById(Long id){
        Customer customer = customerRepository.findById(id)
                .orElseThrow(() -> new ResourceNotFoundException("客户", "id", id));
        return convertToResponse(customer);
    }

    /**
     * 新增客户
     * @param request 客户
     * @return 客户详情
     */
    @Transactional
    public CustomerResponse createCustomer(CustomerCreateRequest request){
        // 检查重复性
        // 按name检查客户是否存在
        if (customerRepository.existsByName(request.getName())){
            throw new DuplicateResourceException("客户",  request.getName());
        }

        // 构建客户实体
        Customer customer = Customer.builder()
                .name(request.getName())
                .email(request.getEmail())
                .phone(request.getPhone())
                .status(request.getStatus())
                .build();
        if (request.getCreatedByUserId() != null){
            User user = userRepository.findById(request.getCreatedByUserId()).orElseThrow(
                    () -> new ResourceNotFoundException("用户", "id", request.getCreatedByUserId())
            );
            customer.setCreatedByUser(user);// 设置创建人
            customer.setUpdatedByUser(user);// 设置更新人
        }else{
            // 从上下文获取当前用户（通过邮箱查询）
            String email = SecurityContextHolder.getContext().getAuthentication().getName();
            User user = userRepository.findByEmail(email)
                    .orElseThrow(() -> new ResourceNotFoundException("当前用户不存在"));
            customer.setCreatedByUser(user);
            customer.setUpdatedByUser(user);
        }

        Customer savedCustomer = customerRepository.save(customer);
        return convertToResponse(savedCustomer);
    }

    /**
     * 更新客户
     */
    @Transactional
    public CustomerResponse updateCustomer(Long id, CustomerUpdateRequest request){
        Customer customer = customerRepository.findById(id)
                .orElseThrow(() -> new ResourceNotFoundException("客户", "id", id));

        // 检查 name 是否重复（排除自己）
        if(request.getName() != null && !request.getName().equals(customer.getName())){
            if(customerRepository.existsByName(request.getName())){
                throw new DuplicateResourceException("客户", request.getName());
            }
        }

        // 更新字段（只更新非空字段）
        if(request.getName() != null){
            customer.setName(request.getName());
        }
        if(request.getEmail() != null){
            customer.setEmail(request.getEmail());
        }
        if(request.getPhone() != null){
            customer.setPhone(request.getPhone());
        }
        if(request.getStatus() != null){
            customer.setStatus(request.getStatus());
        }
        if(request.getUpdatedByUserId() != null){
            User user = userRepository.findById(request.getUpdatedByUserId()).orElseThrow(
                    () -> new ResourceNotFoundException("更新人用户", "id", request.getUpdatedByUserId())
            );
            customer.setUpdatedByUser(user);
        }else{
            // 从上下文获取当前用户（通过邮箱查询）
            String email = SecurityContextHolder.getContext().getAuthentication().getName();
            User user = userRepository.findByEmail(email)
                    .orElseThrow(() -> new ResourceNotFoundException("当前用户不存在"));
            customer.setUpdatedByUser(user);

        }
        Customer updatedCustomer = customerRepository.save(customer);
        return convertToResponse(updatedCustomer);
    }


    /**
     * 删除客户
     * @param id 客户ID
     */
    @Transactional
    public void deleteCustomer(Long id){
        Customer customer = customerRepository.findById(id)
                .orElseThrow(() -> new ResourceNotFoundException("客户", "id", id));
        customerRepository.delete(customer);
    }

    /**
     * 转换为响应对象
     * @param customer 客户
     * @return 响应对象
     */
    public CustomerResponse convertToResponse(Customer customer){
        return CustomerResponse.builder()
                .id(customer.getId())
                .name(customer.getName())
                .email(customer.getEmail())
                .phone(customer.getPhone())
                .status(customer.getStatus())
                .createdAt(customer.getCreatedAt())
                .createdBy(customer.getCreatedByUser() != null ? customer.getCreatedByUser().getUsername() : null)
                .createdByUserId(customer.getCreatedByUser() != null ? customer.getCreatedByUser().getId() : null)
                .updatedAt(customer.getUpdatedAt())
                .updatedBy(customer.getUpdatedByUser() != null ? customer.getUpdatedByUser().getUsername() : null)
                .updatedByUserId(customer.getUpdatedByUser() != null ? customer.getUpdatedByUser().getId() : null)
                .build();
    }
}
